<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Middleware;

use App\Job\WebLogJob;
use App\Service\QueueService;
use Hyperf\Contract\SessionInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class BackendOuthMiddleware implements MiddlewareInterface
{
    #[Inject]
    protected SessionInterface $session;

    /**
     * @var QueueService
     */
    protected $service;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(protected ContainerInterface $container, QueueService $queueService, HttpResponse $response)
    {
        $this->service = $queueService;
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $admin = $this->session->get('admin_user');

        if (! $admin) {
            $data = ['code' => 10002, 'msg' => '令牌已过期, 请重新登录', 'data' => []];

            return $this->response->withStatus(401)->json($data);
        }

        $this->writeLog($request);
        return $handler->handle($request);
    }

    public function writeLog(ServerRequestInterface $request)
    {
        // if ($request->getMethod() != 'GET') {
            $requestH = ApplicationContext::getContainer()->get(RequestInterface::class);
            $header = $requestH->getHeader('User-Agent');
            $routerHander = $request->getAttribute(Dispatched::class)->handler;
            $admin = $this->session->get('admin_user');

            $data = [
                'path' => $requestH->getUri()->getPath(),
                'action' => $routerHander->callback[0] . '::' . $routerHander->callback[1],
                'method' => $requestH->getMethod(),
                'params' => json_encode($requestH->all(), JSON_UNESCAPED_UNICODE),
                'remote_ip' => get_client_ip(),
                'agent' => !empty($header) ? $header[0] : '',
                'user_id' => $admin->id,
                'user_name' => $admin->login_name,
                'operation' => $admin->login_name . $routerHander->options['operation'],
                'type' => '',
            ];

            $this->service->push(WebLogJob::class, $data);
        // }
    }
}
